package com.kly.sc.api.infras.handler;

import com.kly.sc.api.infras.enums.BasicErrorCodeEnum;
import com.kly.sc.api.infras.exception.ApplicationException;
import com.kly.sc.api.infras.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by zcg on 15/10/5.
 */
@ControllerAdvice
public class ErrorHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(ErrorHandler.class);

    /**
     * 业务级异常的捕获
     *
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = ApplicationException.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public ExceptionOutput applicationErrorHandler(ApplicationException e) throws Exception {
        LOGGER.info("统一报错日志, app process error", e);
        return new ExceptionOutput(e.getErrorId(), e.getMessage());
    }

    /**
     * 业务级异常的捕获
     *
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = com.fqgj.exception.common.ApplicationException.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public ExceptionOutput applicationErrorHandler(com.fqgj.exception.common.ApplicationException e) throws Exception {
        LOGGER.info("app process error", e);
        return new ExceptionOutput(e.getErrorId(), e.getMessage());
    }

    /**
     * exception 异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ExceptionOutput errorResponse(HttpServletRequest request, Exception e) {
        LOGGER.error("统一报错日志,uri:" + request.getRequestURI() + ",ip:" + HttpUtils.getIpAddr(request) + ",parameter:" + request.getHeader("basicParams") + "", e);
        return new ExceptionOutput(BasicErrorCodeEnum.UNKNOW_ERROR);
    }

}

